package com.study.controller.system;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.study.common.JsonDTo;
import com.study.common.constant.ResultCode;
import com.study.model.AuthConfig;
import com.study.model.Dynatree;
import com.study.model.Role;
import com.study.service.RoleService;
import com.study.util.AdaptationTree;
import com.study.util.Page;
import com.study.util.StringUtil;

import net.sf.json.JSONArray;

@Controller
public class RoleController {

	@Autowired
	private RoleService roleService;

	private final static Logger logger = Logger.getLogger(RoleController.class);
	
	@RequestMapping(value = "/role/getPaginate")
	public @ResponseBody Page getPaginateRoles(HttpServletRequest request, HttpServletResponse response) {
		Page roles = new Page();
		String pageNo = request.getParameter("pageNo");
		roles.setPageNo(Integer.parseInt(pageNo));
		String searchValue = "%" +StringUtil.getStringObj(request.getParameter("searchValue"))+"%";
		try {
			Map<String,Object> paramMap = new HashMap<String,Object>();
			paramMap.put("page", (roles.getPageNo()-1)*roles.getPageSize());
			paramMap.put("pageSize", roles.getPageSize());
			paramMap.put("searchValue", searchValue);
			List<Role> roleEntitys = roleService.getPaginate(paramMap);
			int total = roleService.getTotal(searchValue);
			roles.setTotalPages(roles.getPages(total));
			roles.getResult().addAll(roleEntitys);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("/role/getPaginate: " + e.getMessage());
		}
		return roles;
	}

	@RequestMapping(value = "/role/isExistByName")
	public @ResponseBody JsonDTo IsExistByName(HttpServletRequest request, HttpServletResponse response,Role role) {
		JsonDTo result = new JsonDTo();
		try {
			Role obj = roleService.isExistByName(role.getRoleName());
			if(StringUtil.isBlank(role.getId())){
				if (obj==null) {
					//可以直接添加
					return JsonDTo.getFail();
				} else {
					//已经存在 不可以添加
					return JsonDTo.getSuccess();
				}
			} else {
				if (obj==null || obj.getId() == role.getId()) {
					//可以直接添加
					return JsonDTo.getFail();
				} else {
					return JsonDTo.getSuccess();
				}
			}
		} catch (Exception e) {
			logger.error("/role/isExistByName: " + e.getMessage());
			result.setCode(ResultCode.fail.value());
			result.setMsg(e.getMessage());
		}
		return result;
	}

	@RequestMapping(value = "/role/save")
	public @ResponseBody JsonDTo save(HttpServletRequest request, HttpServletResponse response,Role role) {
		try {
				roleService.save(role);
				return JsonDTo.getSuccess();
		} catch (Exception e) {
			e.printStackTrace();
			return JsonDTo.getFail();
		}
	}
	
	@RequestMapping(value = "/role/update")
	public @ResponseBody JsonDTo saveorupdate(HttpServletRequest request, HttpServletResponse response,Role role) {
		try {
				roleService.update(role);
				return JsonDTo.getSuccess();
		} catch (Exception e) {
			e.printStackTrace();
			return JsonDTo.getFail();
		}
	}

	@RequestMapping(value = "/role/toAdd")
	public String toAdd(HttpServletRequest request, HttpServletResponse response) {
		return "role/roleAdd.jsp";
	}
	
	@RequestMapping(value = "/role/toEdit")
	public String toEdit(HttpServletRequest request, HttpServletResponse response) {
		request.setAttribute("id", request.getParameter("id"));
		return "role/roleEdit.jsp";
	}
	
	
	@RequestMapping(value = "/role/get")
	public @ResponseBody Role get(HttpServletRequest request, HttpServletResponse response) {
		Role role = null;
		String roleid = request.getParameter("id");
		String selectKeys = "";
		List<Role> roleAuthEntities = null;
		try {
			List<Dynatree> dynatrees = AdaptationTree.getResultTrees(roleService.getAuthconfigs());
			if(roleid.equals("-1")){
				roleAuthEntities = new ArrayList<Role>();
			} else {
				roleAuthEntities = roleService.getByRoleId(Long.valueOf(roleid));
			}
			role = roleService.get(roleid);
			if(role==null){
				role=new Role();
			}
			if (roleAuthEntities != null && roleAuthEntities.size() > 0) {
				for (Role roleAuth : roleAuthEntities) {
					selectKeys += roleAuth.getAuthid() + ",";
					String key = roleAuth.getAuthid() + "";
					setEachSelectKey(dynatrees, key);
				}
			}
			if (selectKeys.lastIndexOf(",") != -1) {
				selectKeys = selectKeys.substring(0, selectKeys.lastIndexOf(","));
			}
			JSONArray jarr = JSONArray.fromObject(dynatrees);
			role.setDynatrees(jarr.toString());
			role.setSelectKeys(selectKeys);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		return role;
	}
	
	
	@RequestMapping(value = "/role/list")
	public String list(HttpServletRequest request, HttpServletResponse response) {
		return "role/roleList.jsp";
	}

	@RequestMapping(value = "/role/removeList")
	public @ResponseBody JsonDTo removeList(HttpServletRequest request, HttpServletResponse response) {
		JsonDTo result = new JsonDTo();
		try {
			roleService.remove(request.getParameter("ids"));
			result.setCode(ResultCode.success.value());
			result.setMsg("删除成功");
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result.setCode(ResultCode.fail.value());
			result.setMsg(e.getMessage());
		}
		return result;
	}

	@RequestMapping(value = "/role/getAllRole")
	public @ResponseBody JsonDTo getAllRole(HttpServletRequest request, HttpServletResponse response) {
		JsonDTo result = new JsonDTo();
		try {
			result.setCode(ResultCode.success.value());
			result.setMsg(ResultCode.success.getDisplay());
			result.setData(roleService.getAllRole());
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result.setCode(ResultCode.fail.value());
			result.setMsg(e.getMessage());
		}
		return result;
	}

	@RequestMapping(value = "/role/allauthconfig",method=RequestMethod.POST)
	public String getAuthconfigEntity(HttpServletRequest request, HttpServletResponse response) {
		response.setContentType("text/html"); 
		response.setCharacterEncoding("UTF-8"); 
		JSONArray jarr;
		try {
			jarr = JSONArray.fromObject(this.getTreeList());
			logger.info(jarr.toString());
			PrintWriter out = response.getWriter();
			out.write(jarr.toString());
			out.flush();
			out.close();
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		return null;
	}

	private List<Dynatree> getTreeList() {
		List<AuthConfig> authconfigEntities = roleService.getAuthconfigs();
		try {
			return AdaptationTree.getResultTrees(authconfigEntities);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return Collections.emptyList();
	}

	private void setEachSelectKey(List<Dynatree> dynatrees, String key) {
		if (dynatrees == null) {
			return;
		}
		for (Dynatree dynatree : dynatrees) {
			if (key.equals(dynatree.getKey())) {
				dynatree.setSelect(true);
				break;
			}
			if (dynatree.getChildren() == null) {
				break;
			}
			for (Dynatree dynatree2 : dynatree.getChildren()) {
				if (key.equals(dynatree2.getKey())) {
					dynatree2.setSelect(true);
					break;
				}
				this.setEachSelectKey(dynatree2.getChildren(), key);
			}
		}
	}
}